const Service = require('egg').Service;
const qs = require('querystring');

class UserService extends Service {
  
  async getUser(query) {
    const { model } = this.ctx;
    
    const user = await model.User.findOne(query).lean();
    
    if (!user) {
      return [];
    }
    return [ user ];
  }

  async updateRoom({ userId, roomId }) {
    const ctx = this.ctx;
    const userQuery = {
      _id: userId,
    };

    const user = await ctx.model.User.findOneAndUpdate(userQuery, {
      room_id: roomId,
    });

    return [ user ];
  }

  async updateUserInfo({ userId, userInfo }) {
    const ctx = this.ctx;
    const userQuery = {
      _id: userId,
    };
    userInfo.has = true;

    const user = await ctx.model.User.findOneAndUpdate(userQuery, {
      user_info: userInfo,
    });
    return [ user ];
  }

  async updateUserByUserId({ userId, accessToken }) {
    const ctx = this.ctx;
    
    const userQuery = {
      _id: userId,
    };

    const user = await ctx.model.User.findOneAndUpdate(userQuery, {
      accessToken: accessToken,
    });

    return [ user ];
  }

  async updateUser({ accessToken, openid, sessionKey }) {
    const ctx = this.ctx;
    
    const userQuery = {
      openid: openid,
    };

    const user = await ctx.model.User.findOneAndUpdate(userQuery, {
      session_key: sessionKey,
      accessToken: accessToken,
    });

    return [ user ];
  }

  async beikeLogin({ token, ucid }) {
    const ctx = this.ctx;

    const userQuery = {
      openid: ucid,
    };

    let user = await ctx.model.User.findOne(userQuery);

    if (!user) {
      user = new this.ctx.model.User();
      user.openid = ucid;
      user.source = 'ke.com'
      user.code = token;
      await user.save();
    }

    return [{ openid: ucid, session_key: token }, { user: user._doc }];
  }

  async wechatLogin({ code }) {
    const ctx = this.ctx;
    // const app = this.app;

    // const param = await ctx.checkToken(app.config.miniapp.secret);

    const params = {
      appid: 'wx9d5e67333d47c866',
      secret: '28ad039b7dc86a4fd9a82d857b4e894b',
      js_code: code,
      'grant_type': 'authorization_code',
    }

    const url = `https://api.weixin.qq.com/sns/jscode2session?${qs.stringify(params)}`;
    const result = await this.ctx.curlGet(url);
    const userQuery = {
      openid: result.openid,
    };

    let user = await ctx.model.User.findOne(userQuery);

    if (!user) {
      user = new this.ctx.model.User();
      user.openid = result.openid;
      await user.save();
    }


    return [ result, { user: user._doc } ];
  }

  newAndSave(name, loginname) {
    const user = new this.ctx.model.User();
    user.name = name;
    user.loginname = loginname;
    return user.save();
  }

  /*
   * 根据用户名列表查找用户列表
   * @param {Array} names 用户名列表
   * @return {Promise[users]} 承载用户列表的 Promise 对象
   */
  async getUsersByNames(names) {
    if (names.length === 0) {
      return [];
    }

    const query = { loginname: { $in: names } };
    return this.ctx.model.User.find(query).exec();
  }
  
  /*
   * 根据登录名查找用户
   * @param {String} loginName 登录名
   * @return {Promise[user]} 承载用户的 Promise 对象
   */
  getUserByLoginName(loginName) {
    const query = { loginname: new RegExp('^' + loginName + '$', 'i') };
    return this.ctx.model.User.findOne(query).exec();
  }

}

module.exports = UserService;
